<?php
/**
 * Created by Yevgen Vershynin.
 * User: Yevgen Vershynin
 * Description: Controller for Product Entity. Controls all operations for incoming requests.
 */
class ProductController
{
    private $productModel;

    public function __construct()
    {
        //Create ProductModel object to use it during request action.
        $this->productModel = new ProductModel();
    }

    public function getAction($request)
    {
        if(isset($request->urlElements[2]))
        {
            //If second argument is set, get Product by id
            $productId = $request->urlElements[2];
            $data["message"] = "here is the info for product " . $productId;
            $product = $this->productModel->getProductById($productId);
            $data["product"] = $product;
        }
        else
        {
            //Second argument not set, means to get the list of Products
            $data["message"] = "you want a list of products";
            $products = $this->productModel->getAllProducts();
            $data["product"] = $products;
        }
        return $data;
    }

    public function postAction($request)
    {
        $data = $request->parameters;

        if(isset($request->urlElements[2]))
        {
            //If second argument is set, perform Update of the Product
            if($this->productModel->updateProduct($data))
            {
                $data['message'] = "This data was submitted";
            }
            else
            {
                $data['message'] = "Data not saved. DB error.";
            }
        }
        else
        {
            $data['message'] = "Data not saved. Product id is not provided.";
        }

        return $data;
    }

    public function putAction($request)
    {
        $data = $request->parameters;

        //Create Product entry with provided parameters
        if($this->productModel->createProduct($data))
        {
            $data['message'] = "This data was submitted";
        }
        else
        {
            $data['message'] = "Data not saved.";
        }

        return $data;
    }

    public function deleteAction($request)
    {
        $data = $request->parameters;

        if(isset($request->urlElements[2]))
        {
            //If second parameter set, perform delete of the product.
            $productId = $request->urlElements[2];

            if($this->productModel->deleteProduct($productId))
            {
                $data['message'] = "This Product was deleted";
            }
            else
            {
                $data['message'] = "This Product was NOT deleted. DB error.";
            }
        }
        else
        {
            $data['message'] = "This Product was NOT deleted. Product id is not provided";
        }

        return $data;
    }
}
